<template>
  <div class="login-bg" :style="'background-image:url(' + bgimg_url + ');'">
    <div class="login-container flex-c-c">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="left" label-width="0px"
        class="demo-ruleForm">
        <h3 class="names">欢迎登录</h3>
        <div class="title">{{ shop_name }}</div>
        <el-form-item prop="account">
          <div class="left-img-input">
            <img class="l-img" src="@/assets/img/login-name.png" />
            <el-input class="l-input" type="text" maxlength="11" v-model="ruleForm.account" auto-complete="off"
              placeholder="请输入手机号">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="verifycode" style="line-height: 0px">
          <div class="left-img-input">
            <img class="l-img" src="@/assets/img/login-code.png" />
            <el-input class="l-input" type="text" maxlength="4" v-model="ruleForm.verifycode" auto-complete="off"
              placeholder="请输入随机码"></el-input>
            <sidentify @click="refreshCode()" :identifyCode="identifyCode"></sidentify>
          </div>
        </el-form-item>
        <el-form-item prop="checkPass">
          <div class="left-img-input">
            <img class="l-img" src="@/assets/img/login-password.png" />
            <el-input class="l-input" type="password" maxlength="6" v-model="ruleForm.checkPass" auto-complete="off"
              placeholder="请输入验证码">
            </el-input>
            <div :class="['get-code-dis', { 'get-code': isGetCode && !btnLoading }]">
              <span v-if="timer ? false : true" @click="getCode()">获取验证码</span>
              <span v-else style="color: #D9DCEA;">{{ timer }}</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <!-- <el-button :class="['login-btn', { 'login-btn-dis ': isLoginDis && !btnLoading }]"
            @click.native.prevent="SubmitFunc" :loading="logining">登录
          </el-button> -->
          <el-button :class="['login-btn', { 'login-btn-dis ': isLoginDis && !btnLoading }]"
            @click.native.prevent="SubmitFuncMobile" :loading="logining">登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import sidentify from "@/components/sidentify.vue";
import IndexApi from "@/api/index.js";
import bgimg from "@/assets/img/login_bg.png";
import UserApi from "@/api/user.js";
import { useUserStore } from "@/store";
import { isPhone } from "@/utils/validate.js";
const { afterLogin } = useUserStore();
export default {
  components: {
    sidentify,
  },
  data() {
    // 验证码自定义验证规则
    const validateVerifycode = (rule, value, callback) => {
      if (value === "") {
        this.refreshCode();
        callback(new Error("请输入验证码"));
      } else if (value !== this.identifyCode) {
        console.log("验证码:", value);
        this.refreshCode();
        callback(new Error("验证码不正确!"));
      } else {
        callback();
      }
    };
    return {
      timer: 0,
      identifyCodes: "1234567890", //验证码的数字库
      identifyCode: "", // 验证码组件传值
      /*是否正在加载*/
      loading: true,
      /*商城名称*/
      shop_name: "",
      /*背景图片*/
      bgimg_url: "",
      /*是否正在提交*/
      logining: false,
      /*表单对象*/
      ruleForm: {
        /*手机号*/
        account: "",
        /*验证码*/
        checkPass: "",
      },
      /*验证规则*/
      rules: {
        /*手机号*/
        account: [
          {
            required: true,
            trigger: "blur",
            // validator: (rule, value, callback) => {
            //   if (value === "") {
            //     callback(new Error("请输入手机号"));
            //   } else if (!isPhone(value)) {
            //     callback(new Error("请输入正确的手机号"));
            //   } else {
            //     callback();
            //   }
            // },
          },
        ],
        /*验证码*/
        checkPass: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
        verifycode: [
          {
            required: true,
            trigger: "blur",
            validator: validateVerifycode,
          },
        ],
      },
      /*基础配置*/
      baseData: {},
    };
  },
  created() {
    this.refreshCode();
    this.getData();
    if (this.$route.query.from && this.$route.query.from == "admin") {
      this.saasLogin();
    }
  },
  mounted() {
    this.identifyCode = "";
    this.makeCode(this.identifyCodes, 4);
  },
  methods: {
    getCode() {
      if (!this.isGetCode || this.btnLoading) {
        return
      }
      let self = this;
      this.btnLoading = true;
      UserApi.getCode({
        app_id: 10001,
        mobile: self.ruleForm.account,
      }, true)
        .then((res) => {
          self.btnLoading = false;
          console.log(res,'ressss',res.data)
          if (res.code == 1) {
            ElMessage({
              message: '短信验证码发送成功',
              type: "success",
            });
            this.countdown(60, () => {
            })
          } else {
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        })
        .catch((error) => {
          self.btnLoading = false;
        });
    },
    countdown(seconds, callback) {
      this.timer = seconds;
      const intervalId = setInterval(() => {
        if (this.timer <= 0) {
          clearInterval(intervalId);
          callback();
        } else {
          this.timer--;
        }
      }, 1000);
    },
    //验证码----start
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
      }
      // console.log("this.identifyCode:", this.identifyCode);
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    /*获取基础配置*/
    getData() {
      let self = this;
      IndexApi.base(true)
        .then((res) => {
          self.loading = false;
          self.shop_name = '崇实易考后台管理系统' || res.data.settings.shop_name;
          if (res.data.settings.shop_bg_img != "") {
            self.bgimg_url = res.data.settings.shop_bg_img;
          } else {
            self.bgimg_url = bgimg;
          }
        })
        .catch((error) => {
          self.loading = false;
        });
    },

    /*登录方法*/
    SubmitFunc(ev) {
      var _this = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.logining = true;
          var Params = {
            username: this.ruleForm.account,
            password: this.ruleForm.checkPass,
          };
          /*调用登录接口*/
          UserApi.login(Params, true)
            .then(async (res) => {
              this.logining = false;
              if (res.code == 1) {
                // /*保存个人信息*/
                // setCookie('userinfo', res.data);
                // /*设置一个登录状态*/
                // setCookie('isLogin', true);
                await afterLogin(res);
                /*跳转到首页*/
                this.$router.push({
                  path: "/",
                });
              } else {
                ElMessage({
                  message: "登录失败",
                  type: "error",
                });
              }
            })
            .catch((error) => {
              //接口调用方法统一处理
              this.logining = false;
            });
        }
      });
    },
    SubmitFuncMobile(ev) {
      if (this.isLoginDis) {
        return false
      }
      var _this = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.logining = true;
          var Params = {
            mobile: this.ruleForm.account,
            code: this.ruleForm.checkPass,
          };
          /*调用登录接口*/
          UserApi.phoneLogin(Params, true)
            .then(async (res) => {
              this.logining = false;
              if (res.code == 1) {
                // /*保存个人信息*/
                // setCookie('userinfo', res.data);
                // /*设置一个登录状态*/
                // setCookie('isLogin', true);
                await afterLogin(res);
                /*跳转到首页*/
                this.$router.push({
                  path: "/",
                });
              } else {
                ElMessage({
                  message: "登录失败",
                  type: "error",
                });
              }
            })
            .catch((error) => {
              //接口调用方法统一处理
              this.logining = false;
            });
        }
      });
    },
    saasLogin() {
      /*调用登录接口*/
      UserApi.saasLogin({}, true)
        .then((res) => {
          console.log(res);
          if (res.code == 1) {
            delCookie("baseInfo");
            /*保存个人信息*/
            setCookie("userinfo", res.data);
            /*设置一个登录状态*/
            setCookie("isLogin", true);
            /*跳转到首页*/
            this.$router.push({
              path: "/",
            });
          } else {
            ElMessage({
              message: "登录失败",
              type: "error",
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  computed: {
    isGetCode() {
      return this.ruleForm.account && isPhone(this.ruleForm.account) && this.ruleForm.verifycode === this.identifyCode;
    },
    isLoginDis() {
      return !(this.ruleForm.account && isPhone(this.ruleForm.account) && this.ruleForm.verifycode === this.identifyCode && this.ruleForm.checkPass.length === 6)
    },
  },
};
</script>

<style lang="scss">
.login-bg {
  width: 100%;
  height: 100%;
  background: no-repeat;
  background-size: cover;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-form-item {
  background: rgba(32, 53, 128, 0.01);
}

.login-bg {
  .el-input__wrapper {
    background: rgba(32, 53, 128, 0.01);
    box-shadow: none !important;
  }
}

.login-container {
  width: 526px;
  height: 100%;
  background: #ffffff;
  border-radius: 9px 0px 0px 9px;
  position: absolute;
  top: 0;
  right: 0;

  .checkbox {
    margin-right: 13px;

    .el-checkbox__inner {
      border-radius: 50%;
      border-color: #5cb85c;
    }

    .el-checkbox__input.is-checked .el-checkbox__inner {
      background-color: #5cb85c;
    }
  }

  .login-btn {
    width: 368px;
    height: 51px;
    background: linear-gradient(135deg, #65B4FF 0%, #3A6AE2 100%);
    border-radius: 5px;
    margin: 0 auto;
    font-size: 18px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #ffffff;
    text-align: center;
    line-height: 1;
    border: none;
  }

  .login-btn-dis {
    background: #DCDCDC;
    color: #333333;
  }

  .names {
    width: 100%;
    height: 56px;
    line-height: 56px;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 40px;
    color: #333333;
    letter-spacing: 5px;
    text-align: center;
    margin-bottom: 11px;
  }

  .title {
    width: 100%;
    height: 28px;
    line-height: 28px;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 20px;
    color: #333333;
    margin-bottom: 40px;
    text-align: center;
  }

  .remember {
    margin: 0px 0px 35px 0px;
  }
}

.left-img-input {
  width: 363px;
  height: 54px;
  line-height: 54px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 14px;
  background: rgba(32, 53, 128, 0.01);
  border-radius: 5px 5px 5px 5px;
  border: 1px solid #d9dcea;

  .l-img {
    width: 20px;
    height: 20px;
    margin-right: 10px;
    flex-shrink: 0;
  }

  .l-input {
    flex: 1;
    border: none;
    background: none;
    font-size: 14px;
    color: #666666;

    input {
      border: 0;
    }
  }

  .el-input__inner {
    border: none;
    padding: 0;
  }
}

.get-code-dis {
  border-left: 1px solid #DCDCDC;
  height: 17px;
  line-height: 17px;
  padding-left: 10px;
  display: inline-block;
  width: 100px;
  text-align: center;
  color: #D9DCEA;
  cursor: no-drop;
}

.get-code {
  color: #3A6AE2;
  cursor: pointer;
}
</style>
